/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.service.tenant.impl;

import cn.hutool.crypto.SecureUtil;
import com.google.common.base.Strings;
import com.je.common.auth.impl.CompanyLevelEnum;
import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.common.base.util.JEUUID;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.rpc.setting.MetaSystemSettingRpcService;
import com.je.rbac.exception.AccountException;
import com.je.rbac.exception.TenantException;
import com.je.rbac.model.Tenant;
import com.je.rbac.service.tenant.RbacTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class RbacTenantServiceImpl implements RbacTenantService {

    @Autowired
    private MetaService metaService;
    @Autowired
    private MetaSystemSettingRpcService metaSystemSettingRpcService;

    @Override
    public List<DynaBean> findAllTenants(int... startAndLimit) {
        int start = 0;
        int limit = -1;
        if(startAndLimit != null){
            start = startAndLimit[0];
            limit = startAndLimit[1];
        }
        return metaService.select("JE_RBAC_TENANT",start,limit);
    }

    @Override
    public DynaBean findTenantById(String tenantId) {
        return metaService.selectOne("JE_RBAC_TENANT", ConditionsWrapper.builder().eq("JE_RBAC_TENANT_ID",tenantId));
    }

    @Override
    public DynaBean findTenantByCode(String code) {
        return metaService.selectOne("JE_RBAC_TENANT", ConditionsWrapper.builder().eq("TENANT_CODE",code));
    }

    @Override
    public DynaBean findTenantByName(String name) {
        return metaService.selectOne("JE_RBAC_TENANT", ConditionsWrapper.builder().eq("TENANT_NAME",name));
    }

    @Override
    public DynaBean findTenantByPhone(String phone) {
        return metaService.selectOne("JE_RBAC_TENANT", ConditionsWrapper.builder().eq("TENANT_CONTACT_PHONE",phone));
    }

    @Override
    public DynaBean findTenantByEmail(String email) {
        return metaService.selectOne("JE_RBAC_TENANT", ConditionsWrapper.builder().eq("TENANT_CONTACT_MAIL",email));
    }

    @Override
    public DynaBean findTenantByFax(String fax) {
        return metaService.selectOne("JE_RBAC_TENANT", ConditionsWrapper.builder().eq("TENANT_FAX",fax));
    }

    @Override
    public List<DynaBean> findTenantBySouce(String sourceCode) {
        return metaService.select("JE_RBAC_TENANT", ConditionsWrapper.builder().eq("TENANT_SOURCE_CODE",sourceCode));
    }

    @Override
    public void openTenant(Tenant tenant) throws TenantException, AccountException {
        //租户
        List<DynaBean> tenantBeans = metaService.select("JE_RBAC_TENANT",ConditionsWrapper.builder()
                .eq("TENANT_CONTACT_PHONE",tenant.getContactPhone())
                .or()
                .eq("TENANT_NAME",tenant.getName())
                .or()
                .eq("TENANT_CONTACT_MAIL",tenant.getContactEmail()));
        if(tenantBeans != null && !tenantBeans.isEmpty()){
            throw new TenantException("已经包含当前租户，请不要重复创建");
        }
        String tenantId = JEUUID.uuid();
        DynaBean tenantBean = new DynaBean("JE_RBAC_TENANT",true);
        tenantBean.set("JE_RBAC_TENANT_ID",tenantId);
        tenantBean.set("TENANT_NAME",tenant.getName());
        tenantBean.set("TENANT_CODE",tenant.getCode());
        tenantBean.set("TENANT_CONTACT_NAME",tenant.getContactName());
        tenantBean.set("TENANT_CONTACT_PHONE",tenant.getContactPhone());
        tenantBean.set("TENANT_CONTACT_MAIL",tenant.getContactEmail());
        tenantBean.set("TENANT_CONTACT_ADDRESS",tenant.getContactAddress());
        tenantBean.set("TENANT_SOURCE_CODE","system");
        tenantBean.set("TENANT_SOURCE_NAME","系统创建");
        tenantBean.set("TENANT_FAX",tenant.getFax());
        tenantBean.set("TENANT_REMARK",tenant.getRemark());
        metaService.insert(tenantBean);

        //用户
        String userId = JEUUID.uuid();
        DynaBean userBean = new DynaBean("JE_RBAC_USER",true);
        userBean.set("JE_RBAC_USER_ID",userId);
        userBean.set("USER_NAME",tenant.getContactName());
        userBean.set("USER_CODE",tenant.getContactPhone());
        userBean.set("USER_PHONE",tenant.getContactPhone());
        userBean.set("USER_MAIL",tenant.getContactEmail());
        userBean.set("USER_ADDRESS",tenant.getContactAddress());
        userBean.set("SY_ORG_ID","systemdepartment");
        metaService.insert(userBean);

        //公司
        long companyCount = metaService.countBySql("SELECT COUNT(*) FROM JE_RBAC_COMPANY WHERE SY_PARENT={0}","ROOT");
        String companyId = JEUUID.uuid();
        DynaBean companyBean = new DynaBean("JE_RBAC_COMPANY",true);
        companyBean.set("JE_RBAC_COMPANY_ID",companyId);
        companyBean.set("COMPANY_NAME",tenant.getName());
        companyBean.set("COMPANY_CODE",tenant.getCode());
        companyBean.set("COMPANY_MANAGER_ID", userId);
        companyBean.set("COMPANY_MANAGER_NAME",tenant.getContactName());
        companyBean.set("COMPANY_MAJOR_ID",userId);
        companyBean.set("COMPANY_MAJOR_NAME",tenant.getContactName());
        companyBean.set("COMPANY_LEVEL_CODE", CompanyLevelEnum.GROUP_COMPANY.getCode());
        companyBean.set("COMPANY_LEVEL_NAME",CompanyLevelEnum.GROUP_COMPANY.getDesc());
        companyBean.set("SY_TENANT_ID",tenantBean.getStr("JE_RBAC_TENANT_ID"));
        companyBean.set("SY_TENANT_NAME",tenant.getName());
        companyBean.set("COMPANY_REMARK",tenant.getRemark());
        companyBean.set("SY_PARENT","ROOT");
        companyBean.set("SY_PARENTPATH","/ROOT");
        companyBean.set("SY_LAYER",1);
        companyBean.set("SY_STATUS","1");
        companyBean.set("SY_NODETYPE","LEAF");
        companyBean.set("SY_PATH","/ROOT/" + companyId);
        companyBean.set("SY_TREEORDERINDEX","000001" + String.format("%06d",companyCount+1));
        metaService.insert(companyBean);

        //部门
        long departmentCount = metaService.countBySql("SELECT COUNT(*) FROM JE_RBAC_COMPANY WHERE SY_PARENT={0}","ROOT");
        String departmentId = JEUUID.uuid();
        DynaBean departmentBean = new DynaBean("JE_RBAC_DEPARTMENT",false);
        departmentBean.set("JE_RBAC_DEPARTMENT_ID",departmentId);
        departmentBean.set("DEPARTMENT_NAME","系统管理部");
        departmentBean.set("DEPARTMENT_SIMPLE_NAME","系统管理部");
        departmentBean.set("DEPARTMENT_CODE","系统管理部");
        departmentBean.set("SY_COMPANY_ID",companyId);
        departmentBean.set("SY_COMPANY_NAME",tenant.getName());
        departmentBean.set("SY_TENANT_ID",tenantId);
        departmentBean.set("SY_TENANT_NAME",tenant.getName());

        departmentBean.set("DEPARTMENT_MAJOR_ID",userId);
        departmentBean.set("DEPARTMENT_MAJOR_NAME",tenant.getContactName());
        departmentBean.set("DEPARTMENT_FUNC_DESC","系统管理部");
        departmentBean.set("DEPARTMENT_REMARK","系统自动创建，系统管理");
        departmentBean.set("SY_GROUP_COMPANY_ID",companyId);
        departmentBean.set("SY_GROUP_COMPANY_NAME",tenant.getName());
        departmentBean.set("SY_ORG_ID","systemdepartment");
        companyBean.set("SY_PARENT","ROOT");
        companyBean.set("SY_PARENTPATH","/ROOT");
        companyBean.set("SY_LAYER",1);
        companyBean.set("SY_STATUS","1");
        companyBean.set("SY_NODETYPE","LEAF");
        companyBean.set("SY_PATH","/ROOT/" + companyId);
        companyBean.set("SY_TREEORDERINDEX","000001" + String.format("%06d",departmentCount+1));
        metaService.insert(departmentBean);

        //部门人员关联关系
        DynaBean departmentUserBean = new DynaBean("JE_RBAC_DEPTUSER",false);
        departmentUserBean.set("JE_RBAC_DEPARTMENT_ID",departmentId);
        departmentUserBean.set("JE_RBAC_USER_ID",userId);
        departmentUserBean.set("DEPTUSER_MAIN_CODE","1");
        departmentUserBean.set("DEPTUSER_MAIN_NAME","是");
        departmentUserBean.set("SY_COMPANY_ID",companyId);
        departmentUserBean.set("SY_COMPANY_NAME",tenant.getName());
        departmentUserBean.set("SY_GROUP_COMPANY_ID",companyId);
        departmentUserBean.set("SY_GROUP_COMPANY_NAME",tenant.getName());
        departmentUserBean.set("DEPTUSER_SFZG_CODE","1");
        departmentUserBean.set("DEPTUSER_SFZG_NAME","是");
        metaService.insert(departmentUserBean);

        String defaultPassword = metaSystemSettingRpcService.requireSettingValue("JE_SYS_PASSWORD");
        if (Strings.isNullOrEmpty(defaultPassword)) {
            throw new AccountException("系统设置默认密码为空！");
        }

        //创建账号
        DynaBean accountBean = new DynaBean("JE_RBAC_ACCOUNT",false);
        accountBean.set("ACCOUNT_NAME",tenant.getContactName());
        accountBean.set("ACCOUNT_CODE",tenant.getContactPhone());
        accountBean.set("ACCOUNT_OPENID",JEUUID.uuid());
        accountBean.set("ACCOUNT_PASSWORD", SecureUtil.md5("kaite2018"));
        accountBean.set("ACCOUNT_PHONE",tenant.getContactPhone());
        accountBean.set("ACCOUNT_MAIL",tenant.getContactEmail());
        accountBean.set("ACCOUNT_AVATAR","");
        accountBean.set("USER_ASSOCIATION_ID",userId);
        accountBean.set("SY_TENANT_ID",tenantId);
        accountBean.set("SY_TENANT_NAME",tenant.getName());
        accountBean.set("ACCOUNT_REMARK","系统创建租户创建");
        accountBean.set("SY_ORG_ID","systemdepartment");
        accountBean.set("SY_ORG_NAME","部门机构");
        metaService.insert(accountBean);
    }

}
